﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServerLibrary.Abstract;
using System.Web;
using System.Net;
using ServerLibrary.Infrastructure;
using System.IO;
namespace ServerLibrary.Concrete
{
    /// <summary>
    /// Implements communicator.
    /// </summary>
    public class Communicator : ICommunicator
    {

        /// <summary>
        /// Gets or sets port.
        /// </summary>
        public uint Port { get { return port; } set { port = value; } }

        #region ICommunicator implementation

        public void Start()
        {
            httpListener.Prefixes.Add("http://+:" + Port +  "/");
            httpListener.Start();
            Console.WriteLine("HttpServer v 1.0\nwaiting for requests.....");
            taskHandler.TaskFinished += new TaskFinishedHandler(OnTaskFinished);
            while (true)
            {
                taskHandler.AddTask(taskManager.GetTask(httpListener.GetContext()));
               
            }
        }
       
        
        public void Stop()
        {
            httpListener.Stop();
            httpListener.Close();
        }

        #endregion

        /// <summary>
        /// Event which raises when task finished.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="arguments"></param>
        protected virtual void OnTaskFinished(object sender, TaskHandlerEventArguments arguments)
        {
           
        }

        #region Fields

        /// <summary>
        ///  Contains HttpListener for listening incoming http requests.
        /// </summary>
        private HttpListener httpListener = new HttpListener();

        /// <summary>
        /// Contains TaskManager for getting tasks.
        /// </summary>
        private ITaskManager taskManager = new TaskManager();

        /// <summary>
        /// Contains TaskHandler,which set task in queue.
        /// </summary>
        private ITaskHandler taskHandler = new TaskHandler();

        /// <summary>
        /// Contains port which server listens.
        /// </summary>
        private uint port;
        
        #endregion
    }
}
